package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func LoginCookie() gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.PostForm("username")
		fmt.Println(username)
		if _, err := c.Cookie(username); err != nil {
			//给客户端设置cookie，存放一小时=3600秒，设置为小于0的数字即为删除
			//第三个参数起：maxAge int 单位秒，path cookie所在目录，domain 域名，
			//secure 是否只能通过https访问，httpOnly 是否允许别人通过js获取自己的cookie
			c.SetCookie(username, c.PostForm("password"), 3600, "/",
				"localhost", false, true)

		}else{
			cookie,_ := c.Cookie(username)
			if cookie != c.PostForm("password"){
				c.String(http.StatusOK,"用户名或密码错误！")
			}
		}
	}
}

func main(){

	e := gin.Default()
	e.LoadHTMLGlob("template/*")
	e.POST("/login",LoginCookie(), func(c *gin.Context) {
		c.String(http.StatusOK,"login : %s",c.PostForm("username"))
	})

	e.Run()
}
